package orm

import (
	"strings"
)

type Deleter[T any] struct {
	builder
	where []Predicate
	table string

	db *DB
}

func NewDeleter[T any](db *DB) *Deleter[T] {
	return &Deleter[T]{
		db: db,
	}
}

func (d *Deleter[T]) Build() (*Query, error) {
	//var sb strings.Builder
	d.sb = &strings.Builder{} // 指针类型一定要初始化
	var err error
	d.model, err = d.db.r.Get(new(T)) // new(T) 生成T的指针
	if err != nil {
		return nil, err
	}
	sb := d.sb
	sb.WriteString("DELETE * FROM ")
	if d.table == "" {
		sb.WriteByte('`')
		sb.WriteString(d.model.TableName)
		sb.WriteByte('`')
	} else {
		//segs := strings.Split(d.table, ".")
		//sb.WriteByte('`')
		sb.WriteString(d.table)
		//sb.WriteByte('`')
	}

	if len(d.where) > 0 {
		sb.WriteString(" WHERE ")
		if err := d.buildPredicates(d.where); err != nil {
			return nil, err
		}
	}

	sb.WriteByte(';')
	return &Query{
		SQL:  sb.String(),
		Args: d.args,
	}, nil
}

//func (s *Deleter[T]) addArg(val any) *Deleter[T] {
//	if s.args == nil {
//		s.args = make([]any, 0, 8)
//	}
//	s.args = append(s.args, val)
//	return s
//}

func (d *Deleter[T]) From(table string) *Deleter[T] {

	return d
}

func (d *Deleter[T]) Where(predicate ...Predicate) *Deleter[T] {
	return d
}
